const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'chatime',
  port: 3306
};

async function insertSampleData() {
  let connection;
  
  try {
    console.log('🔌 连接到数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');
    
    // 插入好友关系
    console.log('👫 插入好友关系...');
    const friendData = [
      ['f1', 'user1', 'user2'],
      ['f2', 'user1', 'user3'],
      ['f3', 'user2', 'user1'],
      ['f4', 'user2', 'user3'],
      ['f5', 'user3', 'user1'],
      ['f6', 'user3', 'user2']
    ];
    
    for (const [id, userId, friendId] of friendData) {
      try {
        await connection.execute(
          'INSERT INTO friends (id, user_id, friend_id, add_time) VALUES (?, ?, ?, NOW())',
          [id, userId, friendId]
        );
        console.log(`✅ 插入好友关系: ${userId} -> ${friendId}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️  好友关系已存在: ${userId} -> ${friendId}`);
        } else {
          console.error(`❌ 插入好友关系失败: ${error.message}`);
        }
      }
    }
    
    // 插入动态
    console.log('📝 插入动态...');
    const dynamicData = [
      ['d1', 'user1', '今日得一款陈年普洱，汤色红浓明亮，香气陈香馥郁，入口醇厚回甘。与三五好友共品，谈古论今，甚是惬意。', 42, 8],
      ['d2', 'user2', '周末和家人一起品茗，感受温馨时光。茶香袅袅，岁月静好。', 35, 5],
      ['d3', 'user3', '新入手一套紫砂壶，泡茶更添风味。欢迎茶友们来品鉴！', 27, 3]
    ];
    
    for (const [id, userId, content, likeCount, commentCount] of dynamicData) {
      try {
        await connection.execute(
          'INSERT INTO dynamics (id, user_id, content, like_count, comment_count, create_time) VALUES (?, ?, ?, ?, ?, NOW())',
          [id, userId, content, likeCount, commentCount]
        );
        console.log(`✅ 插入动态: ${userId}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️  动态已存在: ${userId}`);
        } else {
          console.error(`❌ 插入动态失败: ${error.message}`);
        }
      }
    }
    
    // 插入评论
    console.log('💬 插入评论...');
    const commentData = [
      ['c1', 'd1', 'user2', '此茶我也曾品过，确是上品。不知何处购得？'],
      ['c2', 'd1', 'user3', '好茶配好友，真是人生一大乐事！'],
      ['c3', 'd2', 'user1', '家庭聚会最温暖！'],
      ['c4', 'd2', 'user3', '茶具很有韵味~'],
      ['c5', 'd3', 'user1', '紫砂壶泡普洱最合适！'],
      ['c6', 'd3', 'user2', '下次带点好茶来！']
    ];
    
    for (const [id, dynamicId, userId, content] of commentData) {
      try {
        await connection.execute(
          'INSERT INTO dynamic_comments (id, dynamic_id, user_id, content, create_time) VALUES (?, ?, ?, ?, NOW())',
          [id, dynamicId, userId, content]
        );
        console.log(`✅ 插入评论: ${userId} -> ${dynamicId}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️  评论已存在: ${userId} -> ${dynamicId}`);
        } else {
          console.error(`❌ 插入评论失败: ${error.message}`);
        }
      }
    }
    
    // 插入点赞
    console.log('👍 插入点赞...');
    const likeData = [
      ['like1', 'd1', 'user2'],
      ['like2', 'd1', 'user3'],
      ['like3', 'd2', 'user1'],
      ['like4', 'd2', 'user3'],
      ['like5', 'd3', 'user1'],
      ['like6', 'd3', 'user2']
    ];
    
    for (const [id, dynamicId, userId] of likeData) {
      try {
        await connection.execute(
          'INSERT INTO dynamic_likes (id, dynamic_id, user_id, create_time) VALUES (?, ?, ?, NOW())',
          [id, dynamicId, userId]
        );
        console.log(`✅ 插入点赞: ${userId} -> ${dynamicId}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️  点赞已存在: ${userId} -> ${dynamicId}`);
        } else {
          console.error(`❌ 插入点赞失败: ${error.message}`);
        }
      }
    }
    
    // 插入聊天消息
    console.log('💭 插入聊天消息...');
    const messageData = [
      ['msg1', 'user1', 'user2', '你好，最近怎么样？', 'text', '2025-07-20 02:00:00', true],
      ['msg2', 'user2', 'user1', '挺好的，刚泡了壶茶', 'text', '2025-07-20 02:10:00', true],
      ['msg3', 'user1', 'user2', '什么茶？', 'text', '2025-07-20 02:15:00', true],
      ['msg4', 'user2', 'user1', '普洱，要不要来尝尝？', 'text', '2025-07-20 02:20:00', false],
      ['msg5', 'user1', 'user3', '周末有空吗？', 'text', '2025-07-20 01:00:00', true],
      ['msg6', 'user3', 'user1', '有空，怎么了？', 'text', '2025-07-20 01:10:00', true],
      ['msg7', 'user1', 'user3', '想约你品茶', 'text', '2025-07-20 01:15:00', true],
      ['msg8', 'user3', 'user1', '好啊，正好我新买了茶具', 'text', '2025-07-20 01:30:00', false],
      ['msg9', 'user2', 'user3', '听说你新买了紫砂壶？', 'text', '2025-07-20 00:00:00', true],
      ['msg10', 'user3', 'user2', '是的，泡茶效果很好', 'text', '2025-07-20 00:30:00', true]
    ];
    
    for (const [id, senderId, receiverId, content, type, timestamp, isRead] of messageData) {
      try {
        await connection.execute(
          'INSERT INTO chat_messages (id, sender_id, receiver_id, content, type, timestamp, is_read) VALUES (?, ?, ?, ?, ?, ?, ?)',
          [id, senderId, receiverId, content, type, timestamp, isRead]
        );
        console.log(`✅ 插入消息: ${senderId} -> ${receiverId}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️  消息已存在: ${senderId} -> ${receiverId}`);
        } else {
          console.error(`❌ 插入消息失败: ${error.message}`);
        }
      }
    }
    
    // 插入聊天会话
    console.log('💬 插入聊天会话...');
    const sessionData = [
      ['session1', 'user1', 'user2', '普洱，要不要来尝尝？', '2025-07-20 02:20:00', 1],
      ['session2', 'user2', 'user1', '普洱，要不要来尝尝？', '2025-07-20 02:20:00', 0],
      ['session3', 'user1', 'user3', '好啊，正好我新买了茶具', '2025-07-20 01:30:00', 1],
      ['session4', 'user3', 'user1', '好啊，正好我新买了茶具', '2025-07-20 01:30:00', 0],
      ['session5', 'user2', 'user3', '是的，泡茶效果很好', '2025-07-20 00:30:00', 0],
      ['session6', 'user3', 'user2', '是的，泡茶效果很好', '2025-07-20 00:30:00', 0]
    ];
    
    for (const [id, userId, targetUserId, lastMessage, lastMessageTime, unreadCount] of sessionData) {
      try {
        await connection.execute(
          'INSERT INTO chat_sessions (id, user_id, target_user_id, last_message, last_message_time, unread_count) VALUES (?, ?, ?, ?, ?, ?)',
          [id, userId, targetUserId, lastMessage, lastMessageTime, unreadCount]
        );
        console.log(`✅ 插入会话: ${userId} -> ${targetUserId}`);
      } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          console.log(`⚠️  会话已存在: ${userId} -> ${targetUserId}`);
        } else {
          console.error(`❌ 插入会话失败: ${error.message}`);
        }
      }
    }
    
    console.log('🎉 示例数据插入完成！');
    
    // 验证数据
    console.log('🔍 验证数据...');
    
    const [users] = await connection.execute('SELECT COUNT(*) as count FROM users');
    console.log(`👥 用户数量: ${users[0].count}`);
    
    const [friends] = await connection.execute('SELECT COUNT(*) as count FROM friends');
    console.log(`👫 好友关系数量: ${friends[0].count}`);
    
    const [dynamics] = await connection.execute('SELECT COUNT(*) as count FROM dynamics');
    console.log(`📝 动态数量: ${dynamics[0].count}`);
    
    const [comments] = await connection.execute('SELECT COUNT(*) as count FROM dynamic_comments');
    console.log(`💬 评论数量: ${comments[0].count}`);
    
    const [likes] = await connection.execute('SELECT COUNT(*) as count FROM dynamic_likes');
    console.log(`👍 点赞数量: ${likes[0].count}`);
    
    const [messages] = await connection.execute('SELECT COUNT(*) as count FROM chat_messages');
    console.log(`💭 聊天消息数量: ${messages[0].count}`);
    
    const [sessions] = await connection.execute('SELECT COUNT(*) as count FROM chat_sessions');
    console.log(`💬 聊天会话数量: ${sessions[0].count}`);
    
  } catch (error) {
    console.error('❌ 插入示例数据失败:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 运行插入
if (require.main === module) {
  insertSampleData()
    .then(() => {
      console.log('🎊 示例数据插入脚本执行完成！');
      process.exit(0);
    })
    .catch((error) => {
      console.error('💥 示例数据插入脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = { insertSampleData }; 